<template>
	<div class="search">
		<Header></Header>
		<section>
			<div class="search-top">
				<div class="search-history">
					<i class="fas fa-search"></i>
					<h2>历史搜索</h2>
				</div>
				<i class="far fa-trash-alt" @click="clearSearchHistory"/>
			</div>
			<ul class="search-bottom" v-if="searchArr.length">
				<li v-for="(item,index) in searchArr" :key="index" @click="searchList(item)">{{item}}</li>
			</ul>
			<p v-else >暂无历史搜索</p>
		</section>
	</div>
</template>

<script setup>
	import Header from '@/components/Search/Header.vue'
	import {
		ref,
		onMounted
	} from 'vue'
	let searchArr = ref([])
	// onMounted(() => {
	// 	searchArr.value = JSON.parse(localStorage.getItem(('searchList')) || [])
	// })
	onMounted(() => {
	  try {
	    // 1. 从 localStorage 获取数据
	    const storedData = localStorage.getItem('searchList')
	    
	    // 2. 检查数据是否存在且有效
	    if (storedData) {
	      // 尝试解析 JSON
	      searchArr.value = JSON.parse(storedData)
	    } else {
	      // 如果不存在，初始化为空数组
	      console.warn('searchList 不存在，初始化为空数组')
	      searchArr.value = []
	    }
	  } catch (error) {
	    // 3. 捕获解析错误，防止应用崩溃
	    console.error('解析 searchList 失败:', error)
	    // 初始化为空数组或默认值
	    searchArr.value = []
	  }
	})
	// 清空历史搜索
	import {showConfirmDialog} from 'vant'
	const clearSearchHistory = () =>{
		showConfirmDialog({
			title:'清空历史搜索',
			message:'您确定要清空所有的历史记录吗？'
		}).then(()=>{
			console.log('清空')
			localStorage.removeItem('seaechList')
			searchArr.value = []
		}).catch(()=>{
			console.log('取消')
		})
	}
	// 点击历史搜索跳转
	import {useRouter} from 'vue-router'
	let router = useRouter()
	const searchList = (item) => {
		router.push({
			name:'list',
			query:{
				key:item
			}
		})
	}
	
</script>

<style scoped>
	.search-top {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 18px;
		color: #999;
		padding: 10px 20px;
	}

	.search-history {
		display: flex;
		justify-content: space-around;
		align-items: center;
	}

	.search-history h2 {
		font-size: 16px;
		color: black;
		margin-left: 5px;
	}

	.search-bottom {
		display: flex;
		font-size: 14px;
		padding: 0 20px;
	}

	.search-bottom li {
		border: 1px solid #ccc;
		border-radius: 3px;
		padding: 0 5px;
		margin-right: 10px;
		background-color: white;
	}
	p{
		font-size: 14px;
		color: #999;
		text-align: center;
	}
</style>